/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.actions.manifest;

import com.softwarecraftsmen.inputStreamReaders.Base64EncodingInputStreamReader;
import com.softwarecraftsmen.inputStreamReaders.ReadableData;
import com.softwarecraftsmen.inputStreamReaders.Sha1DigestComputingInputStreamReader;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;
import java.util.jar.Attributes;

public class Sha1DigestManifestWriter
{
	private final Map<String, Attributes> zipEntryNameToAttributes;

	public Sha1DigestManifestWriter(final @NotNull Map<String, Attributes> zipEntryNameToAttributes)
	{
		this.zipEntryNameToAttributes = zipEntryNameToAttributes;
	}

	public void writeSha1DigestToManifest(final @NotNull ReadableData dataToDigest, final @NotNull String zipEntryName)
	{
		if (zipEntryName.startsWith("META-INF"))
		{
			return;
		}
		final Attributes attributesForName;
		if (zipEntryNameToAttributes.containsKey(zipEntryName))
		{
			attributesForName = zipEntryNameToAttributes.get(zipEntryName);
		}
		else
		{
			attributesForName = new Attributes();
			zipEntryNameToAttributes.put(zipEntryName, attributesForName);
		}
		attributesForName.putValue("SHA1-Digest", computeSha1Digest(dataToDigest));
	}

	@NotNull
	private String computeSha1Digest(final ReadableData readableData)
	{
		try
		{
			return readableData.readData(new Base64EncodingInputStreamReader(new Sha1DigestComputingInputStreamReader()));
		}
		catch (IOException e)
		{
			throw new IllegalStateException(e);
		}
	}
}
